<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar">
      <div class="logo">
        <h3 v-if="!isCollapse">DevOps平台</h3>
        <h3 v-else>DO</h3>
      </div>
      
      <el-menu
        :default-active="$route.path"
        :collapse="isCollapse"
        :unique-opened="true"
        router
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
      >
        <!-- 动态渲染用户菜单 -->
        <template v-for="menu in userMenus" :key="menu.id">
          <!-- 一级菜单 -->
          <el-menu-item v-if="menu.level === 1 && !menu.children?.length" :index="menu.path">
            <el-icon>
              <component :is="menu.icon || 'Document'" />
            </el-icon>
            <span>{{ menu.name }}</span>
          </el-menu-item>

          <!-- 有子菜单的一级菜单 -->
          <el-sub-menu v-else-if="menu.level === 1 && menu.children?.length" :index="menu.path">
            <template #title>
              <el-icon>
                <component :is="menu.icon || 'Document'" />
              </el-icon>
              <span>{{ menu.name }}</span>
            </template>
            <el-menu-item
              v-for="child in menu.children"
              :key="child.id"
              :index="child.path"
              class="submenu-item"
            >
              <div class="submenu-content">
                <el-icon class="submenu-icon">
                  <component :is="child.icon || 'Document'" />
                </el-icon>
                <span class="submenu-text">{{ child.name }}</span>
              </div>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleSidebar"
            class="collapse-btn"
          >
            <el-icon><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
          </el-button>
        </div>
        
        <div class="header-right">
          <!-- 通知图标 -->
          <el-badge :value="notificationCount" :hidden="notificationCount === 0" class="notification-badge">
            <el-button type="text" class="notification-btn" @click="showNotifications">
              <el-icon size="18"><Bell /></el-icon>
            </el-button>
          </el-badge>

          <!-- 用户信息下拉菜单 -->
          <el-dropdown @command="handleCommand" class="user-dropdown">
            <div class="user-info">
              <el-avatar :size="36" :src="getAvatarUrl(userInfo.avatar)" class="user-avatar">
                {{ displayName.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ displayName }}</div>
                <div class="user-role">{{ getUserRoleText() }}</div>
              </div>
              <el-icon class="dropdown-arrow"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu class="user-dropdown-menu">
                <div class="dropdown-header" :style="getDropdownHeaderStyle">
                  <el-avatar :size="48" :src="getAvatarUrl(userInfo.avatar)">
                    {{ displayName.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <div class="header-info">
                    <div class="header-username">{{ displayName }}</div>
                    <div class="header-email">{{ userInfo.email || '未设置邮箱' }}</div>
                    <el-tag :type="getUserRoleTagType()" size="small" class="role-tag">
                      {{ getUserRoleText() }}
                    </el-tag>
                  </div>
                </div>
                <el-divider style="margin: 12px 0;" />
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-divider style="margin: 8px 0;" />
                <el-dropdown-item command="logout" class="logout-item">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House,
  User,
  Fold,
  Expand,
  ArrowDown,
  Bell,
  SwitchButton,
  // 只使用确实存在的图标
  UserFilled,
  Document,
  VideoPlay,
  Clock,
  DataBoard,
  Folder,
  Link
} from '@element-plus/icons-vue'
import { authAPI } from '../api/auth'
import { userManagementAPI } from '../api/userManagement'
import eventBus, { EVENT_NAMES } from '../utils/eventBus'
import { getPresetById } from '../config/backgroundPresets'

const router = useRouter()
const isCollapse = ref(false)
const userInfo = ref({})
const userMenus = ref([])
const notificationCount = ref(3) // 模拟通知数量

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 获取显示名称（优先显示姓名，如果没有姓名则显示用户名）
const displayName = computed(() => {
  return userInfo.value.full_name || userInfo.value.username || '未知用户'
})

// 获取下拉菜单头部背景样式
const getDropdownHeaderStyle = computed(() => {
  const settings = userInfo.value.background_settings || {}

  if (!settings || settings.type === 'none') {
    return {
      background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
    }
  }

  if (settings.type === 'preset' && settings.preset_id) {
    const preset = getPresetById(settings.preset_id)
    return preset ? preset.style : {
      background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
    }
  }

  if (settings.type === 'custom' && userInfo.value.background_image) {
    return {
      backgroundImage: `url(${userInfo.value.background_image})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center'
    }
  }

  return {
    background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
  }
})

// 获取用户角色文本
const getUserRoleText = () => {
  if (userInfo.value.is_superuser) {
    return '超级管理员'
  } else if (userInfo.value.is_staff) {
    return '管理员'
  } else {
    return '普通用户'
  }
}

// 获取用户角色标签类型
const getUserRoleTagType = () => {
  if (userInfo.value.is_superuser) {
    return 'danger'
  } else if (userInfo.value.is_staff) {
    return 'warning'
  } else {
    return 'info'
  }
}

// 显示通知
const showNotifications = () => {
  ElMessage.info('通知功能开发中...')
}

// 获取头像完整URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return null

  // 如果已经是完整URL，直接返回
  if (avatar.startsWith('http')) {
    return avatar
  }

  // 构建完整的URL
  const protocol = window.location.protocol
  const hostname = window.location.hostname

  let baseUrl
  if (import.meta.env.DEV && hostname === 'localhost') {
    baseUrl = 'http://localhost:8000'
  } else {
    baseUrl = `${protocol}//${hostname}:8000`
  }

  return `${baseUrl}${avatar}`
}

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      // 先清除本地存储，确保用户能够登出
      const refreshToken = localStorage.getItem('refresh_token')
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')

      // 尝试调用后端登出API，但不依赖其成功
      try {
        if (refreshToken) {
          await authAPI.logout(refreshToken)
        }
      } catch (apiError) {
        console.warn('后端登出API调用失败，但本地登出成功:', apiError)
      }

      ElMessage.success('退出登录成功')
      router.push('/login')
    } catch (error) {
      if (error !== 'cancel') {
        console.error('退出登录失败:', error)
        // 即使出错也强制清除本地存储
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        localStorage.removeItem('user_info')
        router.push('/login')
      }
    }
  } else if (command === 'profile') {
    // 跳转到个人信息页面
    router.push('/profile')
  }
}

const loadUserInfo = async () => {
  try {
    // 检查是否有token，没有token就跳转到登录页面
    const token = localStorage.getItem('access_token')
    if (!token) {
      console.log('没有找到访问令牌，跳转到登录页面')
      router.push('/login')
      return
    }

    const cachedUserInfo = localStorage.getItem('user_info')
    if (cachedUserInfo) {
      userInfo.value = JSON.parse(cachedUserInfo)
    }

    // 从服务器获取最新用户信息
    const response = await authAPI.getUserProfile()
    userInfo.value = response
    localStorage.setItem('user_info', JSON.stringify(response))

    // 加载用户菜单
    await loadUserMenus()
  } catch (error) {
    console.error('获取用户信息失败:', error)
    console.error('错误详情:', error.response?.data || error.message)

    // 如果获取用户信息失败，可能是token过期，清除本地数据
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      console.log('认证失败，清除本地数据并跳转到登录页面')
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      router.push('/login')
    } else if (error.code === 'NETWORK_ERROR' || error.message.includes('Network Error')) {
      console.log('网络错误，使用缓存的用户信息')
      ElMessage.warning('网络连接异常，请检查网络连接')
    } else {
      // 其他错误，显示错误信息但不跳转
      ElMessage.error('获取用户信息失败，请刷新页面重试')
    }
  }
}

// 加载用户菜单
const loadUserMenus = async () => {
  try {
    const response = await userManagementAPI.getUserMenusDetail(userInfo.value.id)

    // 处理API返回的数据结构
    let menuData = []
    if (response.all_menus) {
      // 使用用户有权限的所有菜单
      menuData = response.all_menus
    } else if (Array.isArray(response)) {
      menuData = response
    } else {
      menuData = response.results || []
    }

    userMenus.value = buildMenuTree(menuData)
    console.log('用户菜单加载成功:', userMenus.value)
  } catch (error) {
    console.error('加载用户菜单失败:', error)
    console.error('错误详情:', error.response?.data || error.message)

    // 如果加载菜单失败，尝试加载所有菜单作为备选
    try {
      const allMenusResponse = await userManagementAPI.getAllMenus()
      const allMenus = allMenusResponse.results || allMenusResponse
      userMenus.value = buildMenuTree(allMenus)
      console.log('使用所有菜单作为备选:', userMenus.value)
    } catch (fallbackError) {
      console.error('加载备选菜单也失败:', fallbackError)
      // 最后使用默认菜单
      userMenus.value = getDefaultMenus()
    }
  }
}

// 构建菜单树
const buildMenuTree = (menus) => {
  const menuMap = {}
  const rootMenus = []

  // 创建菜单映射
  menus.forEach(menu => {
    menuMap[menu.id] = { ...menu, children: [] }
  })

  // 构建树结构
  menus.forEach(menu => {
    if (menu.parent) {
      if (menuMap[menu.parent]) {
        menuMap[menu.parent].children.push(menuMap[menu.id])
      }
    } else {
      rootMenus.push(menuMap[menu.id])
    }
  })

  // 排序
  const sortMenus = (menus) => {
    menus.sort((a, b) => a.sort_order - b.sort_order)
    menus.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        sortMenus(menu.children)
      }
    })
  }

  sortMenus(rootMenus)
  return rootMenus
}

// 获取默认菜单（当API失败时使用）
const getDefaultMenus = () => {
  return [
    {
      id: 1,
      name: '仪表盘',
      path: '/',
      icon: 'House',
      level: 1,
      children: []
    }
  ]
}

// 处理用户信息更新事件
const handleUserProfileUpdate = (eventData) => {
  console.log('Layout收到用户信息更新事件:', eventData)
  // 更新用户信息
  if (eventData.userInfo) {
    userInfo.value = { ...userInfo.value, ...eventData.userInfo }
    // 更新本地存储
    localStorage.setItem('user_info', JSON.stringify(userInfo.value))
  }
}

onMounted(() => {
  loadUserInfo()

  // 监听菜单排序更新事件
  window.addEventListener('menu-order-updated', () => {
    console.log('收到菜单更新事件，重新加载菜单')
    loadUserMenus()
  })

  // 监听用户信息更新事件（原有的window事件）
  window.addEventListener('user-info-updated', (event) => {
    console.log('收到用户信息更新事件')
    userInfo.value = { ...userInfo.value, ...event.detail }
  })

  // 监听新的事件总线事件
  eventBus.on(EVENT_NAMES.USER_PROFILE_UPDATED, handleUserProfileUpdate)
})

onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('menu-order-updated', loadUserMenus)
  eventBus.off(EVENT_NAMES.USER_PROFILE_UPDATED, handleUserProfileUpdate)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.sidebar {
  background-color: #304156;
  transition: width 0.3s;
}

.logo {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #2b3a4b 0%, #1e2a3a 100%);
  color: white;
  margin-bottom: 12px;
  position: relative;
  overflow: hidden;
}

.logo::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a, #e6a23c, #f56c6c);
}

.logo h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 1px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.header {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.collapse-btn {
  font-size: 18px;
  color: #606266;
  transition: color 0.3s ease;
}

.collapse-btn:hover {
  color: #409eff;
}

/* 通知按钮样式 */
.notification-badge {
  position: relative;
}

.notification-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  transition: all 0.3s ease;
  background-color: transparent;
}

.notification-btn:hover {
  background-color: #f0f9ff;
  color: #409eff;
}

/* 用户信息区域样式 */
.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid transparent;
}

.user-info:hover {
  background-color: #f0f9ff;
  border-color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.user-avatar {
  margin-right: 12px;
  border: 2px solid #e4e7ed;
  transition: border-color 0.3s ease;
}

.user-info:hover .user-avatar {
  border-color: #409eff;
}

.user-details {
  display: flex;
  flex-direction: column;
  margin-right: 8px;
}

.username {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
  margin: 0;
}

.user-role {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  margin-top: 2px;
}

.dropdown-arrow {
  color: #c0c4cc;
  transition: transform 0.3s ease, color 0.3s ease;
}

.user-info:hover .dropdown-arrow {
  color: #409eff;
  transform: rotate(180deg);
}

/* 用户下拉菜单样式 */
.user-dropdown-menu {
  min-width: 280px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border: 1px solid #e4e7ed;
  padding: 0;
}

.dropdown-header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px 12px 0 0;
}

.header-info {
  margin-left: 12px;
  flex: 1;
}

.header-username {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.header-email {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.role-tag {
  font-weight: 500;
}

.logout-item {
  color: #f56c6c !important;
}

.logout-item:hover {
  background-color: #fef0f0 !important;
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
}

/* 二级菜单样式 */
.submenu-content {
  display: flex;
  align-items: center;
  padding-left: 20px; /* 增加缩进 */
  width: 100%;
}

.submenu-icon {
  font-size: 14px;
  margin-right: 8px;
  opacity: 0.8;
}

.submenu-text {
  font-size: 13px;
  font-weight: 400;
}

/* Element Plus 菜单样式覆盖 */
:deep(.el-menu) {
  border-right: none;
  background-color: #304156;
}

:deep(.el-menu-item) {
  color: #bfcbd9;
  min-height: 48px;
}

:deep(.el-menu-item:hover) {
  background-color: #263445;
}

:deep(.el-menu-item.is-active) {
  background-color: #409EFF;
  color: white;
}

/* 二级菜单项特殊样式 */
:deep(.submenu-item) {
  background-color: rgba(0, 0, 0, 0.1);
  border-left: 3px solid transparent;
  min-height: 40px;
}

:deep(.submenu-item:hover) {
  background-color: rgba(0, 0, 0, 0.2);
  border-left-color: #409EFF;
}

:deep(.submenu-item.is-active) {
  background-color: #409EFF;
  border-left-color: #67C23A;
  color: white;
}

:deep(.submenu-item.is-active .submenu-icon) {
  opacity: 1;
}

:deep(.el-sub-menu__title) {
  color: #bfcbd9;
  font-weight: 500;
  min-height: 56px;
}

:deep(.el-sub-menu__title:hover) {
  background-color: #263445;
}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: #409EFF;
}

/* 一级菜单图标样式 */
:deep(.el-menu-item .el-icon) {
  font-size: 16px;
  margin-right: 8px;
}

:deep(.el-sub-menu__title .el-icon) {
  font-size: 16px;
  margin-right: 8px;
}

/* 展开/收起图标 */
:deep(.el-sub-menu__icon-arrow) {
  font-size: 12px;
  transition: transform 0.3s;
}

:deep(.el-sub-menu.is-opened .el-sub-menu__icon-arrow) {
  transform: rotateZ(180deg);
}

/* 用户下拉菜单项样式 */
:deep(.user-dropdown-menu .el-dropdown-menu__item) {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  font-size: 14px;
  transition: all 0.3s ease;
}

:deep(.user-dropdown-menu .el-dropdown-menu__item .el-icon) {
  margin-right: 8px;
  font-size: 16px;
}

:deep(.user-dropdown-menu .el-dropdown-menu__item:hover) {
  background-color: #f0f9ff;
  color: #409eff;
}

:deep(.user-dropdown-menu .el-divider) {
  margin: 8px 0;
}

/* 通知徽章样式 */
:deep(.notification-badge .el-badge__content) {
  background-color: #f56c6c;
  border: 2px solid #ffffff;
  font-size: 11px;
  height: 18px;
  line-height: 14px;
  min-width: 18px;
  padding: 0 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 0 16px;
  }

  .header-right {
    gap: 12px;
  }

  .user-details {
    display: none;
  }

  .user-info {
    padding: 6px 8px;
  }

  .user-dropdown-menu {
    min-width: 240px;
  }

  .dropdown-header {
    padding: 16px;
  }
}
</style>
